<template>
  <el-dialog :title="showTitle" :visible="dialogVisible" @close="closeDialog" @open="openDialog">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <!-- 完成表单校验需要的前置条件
        - el-form配置model和rules属性
        - el-form-item配置prop属性
        - 表单进行v-model双向绑定
        -->
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetEmployeeSimple } from '@/api/employees'
import { reqAddDepartments, reqGetDepartDetail, reqUpdateDepartments } from '@/api/departments'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      required: true
    },
    depts: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验的函数需要用匿名函数，因为this的指向问题  回调函数中的 this 指向 rule
    // callback() => 校验通过
    // callback(new Error('提示信息')) => 校验未通过
    const validateName = (rule, value, cb) => {
      // if (this.form.id) {
      //   // 编辑
      //   if (this.nodeData.name === value) {
      //     return cb()
      //   }
      // }
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? cb(new Error(`已经有${value}部门名称了`)) : cb()
      let children = []
      if (this.form.id) {
        // 编辑
        if (this.nodeData.name === value) {
          return cb()
        }
        // 获取同级部门
        children = this.depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        // 新增  获取子部门
        children = this.depts.filter(item => item.pid === this.nodeData.id)
      }
      const isRepeat = children.some(item => item.name === value)
      isRepeat ? cb(new Error(`同级部门下已经有${value}部门名称了`)) : cb()
    }
    const validateCode = (rule, value, cb) => {
      if (this.form.id) {
        // 编辑
        if (this.nodeData.code === value) {
          return cb()
        }
      }
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? cb(new Error(`已经有${value}部门编码了`)) : cb()
    }
    return {
      options: [],
      form: { code: '', introduce: '', name: '', manager: '' },
      rules: {
        code: [
          { required: true, message: '请输入部门名称', trigger: ['change', 'blur'] },
          { min: 1, max: 50, trigger: ['change', 'blur'], message: '请输入1~50位字符' },
          { validator: validateCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门名称', trigger: ['change', 'blur'] },
          { min: 1, max: 300, trigger: ['change', 'blur'], message: '请输入1~300位字符' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: ['change', 'blur'] },
          { min: 1, max: 50, trigger: ['change', 'blur'], message: '请输入1~50位字符' },
          { validator: validateName, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门名称', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  async created() {
    this.getEmployeeSimple()
  },
  methods: {
    // 开启dialog
    openDialog() {
      // this.getEmployeeSimple()
    },
    // 关闭dialog
    closeDialog() {
      this.$emit('update:dialogVisible', false)
      // 重置表单 清空校验结果
      this.$refs.deptForm.resetFields()
      // 重置form内容
      this.form = { code: '', introduce: '', name: '', manager: '' }
    },
    // 获取员工简单列表
    async getEmployeeSimple() {
      const { data } = await reqGetEmployeeSimple()
      this.options = data
    },
    async getDepartDetail(id) {
      const { data } = await reqGetDepartDetail(id)
      // console.log(data)
      this.form = data
    },
    submit() {
      this.$refs.deptForm.validate(async(flag) => {
        if (flag) {
          // 校验通过
          // console.log('OK')
          if (!this.form.id) {
            // 新增
            await reqAddDepartments({ ...this.form, pid: this.nodeData.id })
            this.$message.success('新增部门成功')
          } else {
            // 编辑
            await reqUpdateDepartments(this.form)
            this.$message.success('修改部门成功')
            // console.log(1)
          }
          this.$emit('add-depts')
          this.closeDialog()
          // console.log(2)
        } else {
          console.log('no')
        }
      })
    }
  }
}
</script>

<style>

</style>
